﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;

namespace K3R.Imaging {
	[DataContract]
	public class ImageBuilder {
		#region Properties
		[DataMember(Name = "imagePath")] public string ImagePath { get; set; }
		[DataMember(Name = "backgroundColour")] public Color BackgroundColour { get; set; }
		[DataMember(Name = "height")] public int Height { get; set; }
		[DataMember(Name = "width")] public int Width { get; set; }
		[DataMember(Name = "format")] public ImageFormat Format { get; set; }
		[DataMember(Name = "rectangleType")] public RectangleType RectangleType { get; set; }
		[DataMember(Name = "centre")] public bool Centre { get; set; }
		#endregion

		#region Constructors
		public ImageBuilder() { }
		#endregion

		#region Instance
		public Bitmap CreateBitmap() {
			Bitmap bitmap = new Bitmap(Width, Height);

			if (File.Exists(ImagePath)) {
				using (Graphics graphic = Graphics.FromImage(bitmap)) {
					graphic.Clear(BackgroundColour);
					using (Bitmap image = new Bitmap(ImagePath)) {
						int imageHeight = image.Height;
						int imageWidth = image.Width;

						graphic.SmoothingMode = SmoothingMode.AntiAlias;
						graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
						graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

						graphic.DrawImage(image, Dimensions.CreateRectangle(RectangleType, Height, Width,
							imageHeight, imageWidth, Centre));
					}
				}
			}

			return bitmap;
		}

		public void Save(Stream stream) {
			using (var bitmap = CreateBitmap()) {
				bitmap.Save(stream, Format);
			}
		}

		public void Save(string path) {
			using (var bitmap = CreateBitmap()) {
				bitmap.Save(path, Format);
			}
		}

		public Bitmap SaveAndReturn(string path) {
			var bitmap = CreateBitmap();
			bitmap.Save(path, Format);
			return bitmap;
		}
		#endregion
	}
}
